<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action=""
      list-type="picture-card"
      :on-success="handleAvatarSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-progress="onProgress"
      :file-list="fileList"
      :http-request="onUpload"
      :on-change="onChange"
      :before-upload="onBeforeUpload"
      :class="{disable: fileList.length > 0}"
    >
      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-progress v-show="showPercent" :percentage="percent" style="width:198px"></el-progress>
    <el-dialog title="预览头像" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: 'AKIDyObXDckbBVYJn1ye3B2cvwhBOKzNUKtB', // 桶秘钥
  SecretKey: '2oIWS7VcS1JK4XjeIfla8xVmmVx82g38'
})
// 上传关键点
// 1.选取文件(不需要自己做,el-upload已经完成了)
// 2.得到文件对象
// 3.使用npm包
export default {
  name: 'UpdateImage',
  components: {},
  props: {
  },
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      showPercent: false,
      percent: 0
    }
  },
  created() {},
  mounted() {},
  methods: {
    onBeforeUpload({ type, size }) {
      console.log('onBeforeUpload', type, size)
      if (!['image/jpeg', 'image/gif', 'image/bmp', 'image/png'].includes(type)) {
        this.$message.error('文件类型不对')
        return false
      }
      if (size > 5 * 1024 * 1024) {
        this.$message.error('文件太大')
        return false
      }
    },
    onProgress() {

    },
    onChange(file, fileList) {
      this.fileList.push({ url: file.url })
    },
    onUpload({ file }) { // 结构出里面的file文件
      this.showPercent = true
      cos.uploadFile({
        Bucket: 'rzzt-1314095582', /* 填写自己的bucket，必须字段 */ // 桶名称
        Region: 'ap-chengdu', /* 存储桶所在地域，必须字段 */ // 桶地域
        Key: Date.now() + file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        this.showPercent = false
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          this.fileList[0].url = 'http://' + data.Location
        }
      })
    },
    handleAvatarSuccess(res, file) {
      this.showPercent = true
      console.log(file)
    //   this.imageUrl = URL.createObjectURL(file.raw)
    },
    // beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg'
    //   const isLt2M = file.size / 1024 / 1024 < 2

    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!')
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!')
    //   }
    //   return isJPG && isLt2M
    // },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.fileList = []
    }

  }
}
</script>

<style lang="scss" scoped>
 ::v-deep .avatar-uploader.disable .el-upload--picture-card{
    display: none;
 }
</style>
